package com.tedu.project5.controller;


import com.tedu.project5.common.Result;
import com.tedu.project5.mapper.DdUserMapper;
import com.tedu.project5.model.DdUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired(required = false)
    private DdUserMapper ddUserMapper;

    /**
     * 登录失败返回 401 以及提示信息.
     * @return the rest
     */
    @PostMapping("/failure")
    public Result loginFailure() {
        System.out.println("登录失败了");
        return Result.error("登录失败");
    }

    /**
     * 登录成功后拿到个人信息
     * @return the rest
     */
    @PostMapping("/success")
    public Result loginSuccess() {
        System.out.println("登录成功了");
        // 登录成功后用户的认证信息 UserDetails会存在 安全上下文寄存器 SecurityContextHolder 中
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = ((UserDetails) principal).getUsername();
        DdUser ddUser = ddUserMapper.findUserByUserName(username);
        // 脱敏
        ddUser.setPassword("暂不显示");
        return Result.ok("登录成功", ddUser);
    }
}